<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Admin;
use App\Models\School;
use App\Models\WorkUser;
use App\Models\SchoolUser;
use App\Models\WorkTicketDetail;
use App\Models\WorkTicketTransfer;
use App\Enums\WorkTicketStatusEnum;
use App\Admin\Renderable\SchoolTable;
use App\Admin\Export\WorkTicketExport;
use App\Admin\Renderable\StudentTable;
use App\Admin\Repositories\WorkTicket;
use App\Admin\Renderable\WorkUserTable;
use App\Models\WorkTicket as WorkTicketModel;
use Dcat\Admin\Http\Controllers\AdminController;

/**
 * @mixin \App\Models\WorkTicket
 */
class WorkTicketController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WorkTicket(['school', 'schoolUser', 'workUser', 'adminUser']), function (Grid $grid) {
            $grid->column('id')->sortable();
            if (Admin::user()->isRole('administrator')) {
                $grid->column('adminUser.username', '客服');
            } else {
                $grid->model()->where('admin_user_id', Admin::user()->id);
            }
            $grid->column('code', '工单号');
            $grid->column('school.name', '学校');
            $grid->column('schoolUser.real_name', '学生');
            $grid->column('schoolUser.account', '上网账号');
            $grid->column('room_number', '房间号');
            $grid->column('contact_name', '联系人');
            $grid->column('contact_tel', '联系电话');
            $grid->column('content', '内容')->limit(30)->expand(function () {
                return $this->content;
            });
            $grid->column('workUser.real_name', '维修人员');
            $grid->column('status', '状态')->using(WorkTicketStatusEnum::asSelectArray());
            $grid->column('finish_at', '完成时间')->format('Y-m-d H:i:s');
            $grid->column('created_at', '创建时间')->format('Y-m-d H:i:s');
            $grid->column('updated_at', '更新时间')->format('Y-m-d H:i:s');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('id')->width(2);
                $filter->like('code', '工单号')->width(2);
                $filter->like('school.name', '学校')->width(2);
                $filter->like('schoolUser.real_name', '学生')->width(2);
                $filter->like('schoolUser.account', '上网账号')->width(2);
                $filter->like('schoolUser.id_card', '身份证号')->width(2);
                $filter->like('workUser.real_name', '维修人员')->width(2);
                $filter->like('room_number', '房间号')->width(2);
                $filter->like('contact_name', '联系人')->width(2);
                $filter->like('contact_tel', '联系电话')->width(2);
                $filter->in('status', '状态')->multipleSelect(WorkTicketStatusEnum::asSelectArray())->width(4);
                $filter->between('finish_at', '完成时间')->date()->width(4);
                $filter->between('created_at', '创建时间')->date()->width(4);
                $filter->between('updated_at', '更新时间')->date()->width(4);
            });
            if (Admin::user()->can('workTicket-download') || Admin::user()->isRole('administrator')) {
                $grid->allowExporter();
                $grid->export(new WorkTicketExport());
            }
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $builder = new WorkTicketModel();
        $builder->with('school', 'schoolUser', 'workUser', 'details', 'images', 'transfers', 'adminUser');
        // $builder->where('id', $id);
        // $builder->first();
        // dd($builder);
        return Show::make($id,$builder, function (Show $show) {
            $show->field('id');
            if (Admin::user()->isRole('administrator')) {
                $show->field('username', '客服')->as(function () {
                    return $this->adminUser->username;
                });
            }
            $show->field('code', '工单号');
            $show->field('school.name', '学校')->as(function () {
                return $this->school->name;
            });
            $show->field('schoolUser.real_name', '学生')->as(function () {
                return $this->schoolUser->real_name;
            });
            $show->field('room_number', '房间号');
            $show->field('contact_name', '联系人');
            $show->field('contact_tel', '联系电话');
            $show->field('content', '内容');
            $show->field('images', '图片')->as(function () {
                return $this->images->pluck('url');
            })->image();
            $show->field('workUser.real_name', '维修人员')->as(function () {
                return $this->workUser->real_name;
            });
            $show->field('status', '状态')->using(WorkTicketStatusEnum::asSelectArray());
            $show->field('finish_at', '完成时间');
            $show->field('created_at', '创建时间');
            $show->field('updated_at', '更新时间');

            $show->relation('details', '详情', function ($model) {
                $grid = new Grid(new WorkTicketDetail(['related']));
                $grid->model()->where('work_ticket_id', $model->id);
                // $grid->setResource('work-ticket-details');
                $grid->id();
                $grid->column('related', '操作人')->display(function ($model) {
                    if ($model->related instanceof SchoolUser) {
                        return $model->related->real_name;
                    } elseif ($model->related instanceof WorkUser) {
                        return $model->related->real_name;
                    } else {
                        return $model->related->username;
                    }
                });
                $grid->column('content', '内容')->limit(30)->expand(function ($model) {
                    return $model->content;
                });
                $grid->column('images', '图片')->image(function ($model) {
                    return $model->images->pluck('url');
                });
                $grid->column('created_at', '创建时间')->format('Y-m-d H:i:s')->sortable();
                $grid->column('updated_at', '更新时间')->format('Y-m-d H:i:s');
                $grid->disableActions();
                return $grid;
            });

            $show->relation('transfers', '转单', function ($model) {
                $grid = new Grid(new WorkTicketTransfer(['fromWorkUser', 'toWorkUser']));
                $grid->model()->where('work_ticket_id', $model->id);
                // $grid->setResource('work-ticket-transfers');
                $grid->id();
                $grid->column('fromWorkUser.real_name', '转单人');
                $grid->column('toWorkUser.real_name', '接单人');
                $grid->column('status', '状态')->using(WorkTicketStatusEnum::asSelectArray());
                $grid->column('remark', '内容');
                $grid->column('accept_at', '接单时间')->format('Y-m-d H:i:s');
                $grid->column('reject_at', '拒绝时间')->format('Y-m-d H:i:s');
                $grid->column('created_at', '创建时间')->format('Y-m-d H:i:s')->sortable();
                $grid->column('updated_at', '更新时间')->format('Y-m-d H:i:s')->sortable();
                $grid->disableActions();
                return $grid;
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WorkTicket(), function (Form $form) {
            $form->display('id');



            if ($form->isCreating()) {
                $form->hidden('code')->value(function () {
                    return 'W' . date('Ymd') . str_pad(WorkTicketModel::max('id') + 1, 4, '0', STR_PAD_LEFT);
                });
                $form->hidden('admin_user_id')->value(Admin::user()->id);
            } else {
                $form->display('code', '工单号');
                if (!Admin::user()->isRole('administrator')) {
                    $form->hidden('admin_user_id')->value(Admin::user()->id);
                }
            }

            $form->selectTable('school_id', '选择学校')->title('选择学校')
                ->from(SchoolTable::make())
                ->options(function ($v) {
                    if (!$v) {
                        return [];
                    }

                    $arr = School::find($v)->pluck('name', 'id');
                    return $arr;
                })->required();

            if ($form->isCreating()) {
                $form->text('contact_name', '学生姓名')->required();
                $form->text('student_account', '上网账号')->required();
                $form->text('contact_tel', '学生手机')->required();
                $form->text('room_number', '房间号')->required();
                $form->hidden('school_user_id');
                $form->submitted(function (Form $form) {
                    $studentName = $form->input('contact_name');
                    $studentAccount = $form->input('student_account');
                    $studentTel = $form->input('contact_tel');
                    $schoolId = $form->input('school_id');

                    $student = SchoolUser::where('school_id', $schoolId)
                        ->where('real_name', $studentName)
                        ->where('account', $studentAccount)
                        ->first();
                    if (!$student instanceof SchoolUser) {
                        $student = new SchoolUser();
                        $student->school_id = $schoolId;
                        $student->real_name = $studentName;
                        $student->account = $studentAccount;
                        $student->tel = $studentTel;
                        $student->save();
                    }

                    $form->deleteInput('student_account');

                    $form->school_user_id = $student->id;
                });
            } else {
                $form->selectTable('school_user_id', '选择学生')->title('选择学生')
                    ->from(StudentTable::make())
                    ->options(function ($v) {
                        if (!$v) {
                            return [];
                        }

                        $arr = SchoolUser::find($v)->pluck('real_name', 'id');
                        return $arr;
                    })->required();
                $form->text('contact_name', '联系人')->required();
                $form->text('contact_tel', '联系电话')->required();
                $form->select('status', '状态')->options(WorkTicketStatusEnum::asSelectArray());
            }


            $form->selectTable('work_user_id', '选择维修人员')->title('选择维修人员')
                ->from(WorkUserTable::make())
                ->options(function ($v) {
                    if (!$v) {
                        return [];
                    }

                    $arr = WorkUser::find($v)->pluck('real_name', 'id');
                    return $arr;
                })->default(0);

            $form->textarea('content', '内容')->required();
            $form->display('created_at', '创建时间');
            $form->display('updated_at', '更新时间');
        });
    }
}